package com.heyqing.topic.TwoSum_0001;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:TwoSum_0001
 * Package:com.heyqing
 * Description:
 *
 * @Date:2024/5/15
 * @Author:Heyqing
 */
public class TwoSum_0001 {
    /**
     * 哈希表
     *
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        //使用哈希表
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int subTwo = target - nums[i];
            Integer index = map.get(subTwo);
            if (index != null && index != i) {
                result[0] = i;
                result[1] = index;
                return result;
            }
        }
        return null;
    }
}
